package com.gaoyi.basemodule.basefragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.viewbinding.ViewBinding;

import com.gaoyi.basemodule.baseUtil.ActivityUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Fragment嵌套Fragment
 * @param <V>
 */
public abstract class BaseViewParentFragment<V extends ViewBinding> extends BasePermissionFragment {

    protected V mBinding;
    protected FragmentActivity mContext;
    protected NavController mController;
    protected Fragment mFragment;
    private List<Fragment> mFragmentList;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = requireActivity();
        mFragmentList = new ArrayList<>();
        initFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = getViewBinding();
        initView();
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mController = Navigation.findNavController(view);
        initData();
    }

    protected abstract V getViewBinding();

    protected @IdRes abstract int getFragmentId();

    protected abstract void initView();

    protected abstract void initFragment();

    protected abstract void initData();

    private Fragment getFragment(int index) {
        return mFragmentList.get(index);
    }

    protected void setFragment(Fragment fragment) {
        mFragmentList.add(fragment);
    }

    protected void showFragment(int index) {
        Fragment toFragment = getFragment(index);
        if (mFragment != toFragment) {
            FragmentManager fm = getChildFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            if (mFragment != null) {
                transaction.hide(mFragment);
            }
            mFragment = toFragment;
            if (toFragment.isAdded()) {
                transaction.show(toFragment);
            } else {
                transaction.add(getFragmentId(), toFragment);
            }
            transaction.commit();
        }
    }

    @Override
    public void onDestroyView() {
        ActivityUtil.getInstance().removeChildFragment(this);
        super.onDestroyView();
    }
}
